#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include "tp_socket.h"


void diep(char *s) {
    perror(s);
    exit(1);
}


int main(int argc, char** argv){
    //tempo inicio
    struct timeval tv;
    double curtime, totaltime;
    gettimeofday(&tv,NULL);
    curtime= tv.tv_sec+ tv.tv_usec/1e6;
    //

    if (argc < 5){
        printf("./cliente host_do_servidor porto_servidor nome_arquivo tam_buffer\n");
        exit(1);
    }

    tp_init();

    //Atribuição de Parametros
    char* serv_host = argv[1];

    unsigned short int serv_port;
    serv_port = htons(atoi(argv[2]));

    char *fileName;
    fileName = argv[3];

    int buffer_size = atoi(argv[4]);
    

    //inicializacao do socket
    int sock;
    struct sockaddr_in serv_addrin;
    tp_build_addr(&serv_addrin, serv_host, serv_port);

    if ((sock = tp_socket(serv_port)) < 0)
        diep("socket");

    ////abre o arquivo
    //FILE *fileIn;
    //if( (fileIn = fopen(fileName,"w+")) == NULL ){
    //    close(sock);
    //    close(fileIn);
    //    perror("fopen");
    //    exit(1);
    //}
    //printf("File Open: %s\n", fileName);
    ////

    //recebendo arquivo
    char* buffer;
    buffer = (char*)malloc(sizeof(char)*buffer_size);

    int i;
    for(i=0;i<10;i++){
        printf("sending packet %d\n",i);
        if (tp_sendto(sock, buffer, buffer_size, &serv_addrin) < 0)
            diep("sendto");
    }
    close(sock);

    //tempo fim
    double endtime;
    gettimeofday(&tv,NULL);
    endtime= tv.tv_sec+ tv.tv_usec/1e6;
    totaltime= (endtime - curtime);
    //

    //printf("Buffer = \%5u byte(s), \%.3f kbps (\%u bytes em \%.6f s)\n", buffer_size, (received / totaltime), received, totaltime);
//    printf("\%5u \%.2f \%u\n", buffer_size, (received / totaltime), received);
    //printf("\%.2f\n", (received / totaltime));
    exit(0);
}
